<template>
  <!--评分权重设置-->
  <div class="edu-page-warp score-weight-setting">
    <!--修改成绩专业比例 弹框-->
    <edu-dialog :title="$t('graduationDesign.modifyResultMajorRatio')" width="50%" @close="closeDialog" :visible="scoreDialogVisible">
      <el-card shadow="never" v-if="actionType === 'BATCH_EDIT'">
        <el-row>
          <el-col>
            <div class="selected-data">{{$t('graduationDesign.selectedCollegeAndMajor')}}</div>
          </el-col>
        </el-row>
        <edu-table ref="tutorGuideLimitTable" :data="scoreSettingForm.settingList" :pagination="false" :selection="false" :order="false">
          <edu-table-column :label="$t('graduationDesign.college')" prop="collegeI18n" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.major')" prop="subjectName" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.excellent')" prop="excellentRatio" min-width="100">
            <template slot-scope="scope">
              <span :class="scope.row.isDefaultExcellent ? '' : 'ratio-color'">{{`${fixDecimalMul(scope.row.excellentRatio, 100)}%`}}</span>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.good')" prop="fineRatio" min-width="100">
            <template slot-scope="scope">
              <span :class="scope.row.isDefaultFine ? '' : 'ratio-color'">{{`${fixDecimalMul(scope.row.fineRatio, 100)}%`}}</span>
            </template>
          </edu-table-column>
        </edu-table>
      </el-card>
      <el-card shadow="never">
        <el-form :model="scoreSettingForm" ref="scoreSettingForm" :rules="scoreSettingRules" label-position="right" label-suffix="：" label-width="100px">
          <el-row>
            <el-col>
              <el-form-item :label="$t('graduationDesign.excellentPercent')" prop="excellentRatio">
                <el-input v-model="scoreSettingForm.excellentRatio" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item :label="$t('graduationDesign.goodPercent')" prop="fineRatio">
                <el-input v-model="scoreSettingForm.fineRatio" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div slot="buttons">
        <el-button @click="closeDialog">{{$t('graduationDesign.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('graduationDesign.confirm')}}</el-button>
      </div>
    </edu-dialog>

    <condition-card @reset="reset" @search="searchList" label-width="110px">
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('graduationDesign.graduationYear')">
            <el-date-picker class="search-item" v-model="queryForm.grade" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('graduationDesign.college')">
            <el-select v-model="queryForm.college" @change="handleCollegeChange" filterable class="search-item" clearable>
              <el-option v-for="item in source.collegeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('graduationDesign.major')">
            <el-select v-model="queryForm.subjectId" filterable class="search-item" clearable>
              <el-option v-for="item in source.subjectOptions" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <el-card shadow="never">
      <div class="edu-page-title">{{$t('graduationDesign.scoreWeightSetting')}}</div>
      <div class="edu-opertion-bar">
        <div class="float-right">
          <el-button @click="onExport">{{$t('graduationDesign.export')}}</el-button>
          <el-button type="primary" @click="onBatchEdit">{{$t('graduationDesign.modify')}}</el-button>
          <el-button type="primary" @click="onCopy">{{$t('graduationDesign.copy')}}</el-button>
        </div>
      </div>
      <edu-table ref="scoreSettingTable" :url="getList" @selection-change="handleSelectChange">
        <edu-table-column :label="$t('graduationDesign.college')" prop="collegeI18n" min-width="100"></edu-table-column>
        <edu-table-column :label="$t('graduationDesign.major')" prop="subjectName" min-width="100"></edu-table-column>
        <edu-table-column :label="$t('graduationDesign.excellent')" prop="excellentRatio" min-width="100">
          <template slot-scope="scope">
            <span :class="scope.row.isDefaultExcellent ? '' : 'ratio-color'">{{`${fixDecimalMul(scope.row.excellentRatio, 100)}%`}}</span>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('graduationDesign.good')" prop="fineRatio" min-width="100">
          <template slot-scope="scope">
            <span :class="scope.row.isDefaultFine ? '' : 'ratio-color'">{{`${fixDecimalMul(scope.row.fineRatio, 100)}%`}}</span>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('graduationDesign.operation')" min-width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="onEdit(scope.row)">{{$t('graduationDesign.modify')}}</el-button>
          </template>
        </edu-table-column>
      </edu-table>
    </el-card>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/scoreWeightSetting";
import UTILS from "common/src/utils/utils";
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  name: 'scoreWeightSetting',
  data() {
    const validateInteger = (rule, value, callback) => {
      const patternInteger = /^(((\d|[1-9]\d)(\.\d{1})?)|100|100.0)$/;
      if (patternInteger.test(value) || !value) {
        return callback();
      } else {
        return callback(new Error($t('graduationDesign.excellentRatioInteger')));
      }
    };
    return {
      getList: '/api/designservice/scoreWeight/list',
      api: API,
      queryForm: {
        grade: '',
        college: '',
        subjectId: ''
      },
      source: {
        collegeOptions: [], // 学院
        subjectOptions: [] // 专业
      },
      scoreSelectedData: [], // 勾选的列表数据
      scoreSettingForm: {
        settingList: [],
        excellentRatio: '',
        fineRatio: ''
      },
      actionType: 'EDIT',
      scoreSettingRules: {
        excellentRatio: [
          { required: true, message: this.$t('graduationDesign.pleaseEnter'), trigger: "blur" },
          { validator: validateInteger, trigger: 'blur' }
        ],
        fineRatio: [
          { required: true, message: this.$t('graduationDesign.pleaseEnter'), trigger: "blur" },
          { validator: validateInteger, trigger: 'blur' }
        ]
      },
      scoreDialogVisible: false,
      activeAuthId: '',
      currentGrade: ''
    };
  },
  mounted() {
    this.activeAuthId = localStorage.activeAuthId;
    this.currentGrade = new Date().getFullYear() + '';
    this.queryForm.grade = this.currentGrade;
    this.searchList();
    this.getCollege();
  },
  methods: {
    searchList() {
      this.$refs.scoreSettingTable.search(this.queryForm);
    },
    reset() {
      this.queryForm = {
        grade: '',
        college: '',
        subjectId: ''
      };
      this.source.subjectOptions = [];
      this.queryForm.grade = this.currentGrade;
      this.searchList();
    },
    handleSelectChange(val) {
      this.scoreSelectedData = val;
    },
    /**小数精度缺失-乘法 修复
     * ratio 优良占比（最多三位小数）
     * percent 百分比100
     */
    fixDecimalMul(ratio, percent) {
      let times = 0; // 几次方
      let _ratio = ratio.toString();
      let _percent = percent.toString();
      if (_ratio.split(".").length > 1) {
        times += _ratio.split(".")[1].length;
      }
      return Number(_ratio.replace(".", "")) * Number(_percent.replace(".", "")) / Math.pow(10, times);
    },
    // 查学院
    getCollege() {
      const params = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX"]
      };
      this.api.queryDic(params).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            { collegeOptions: 'X_YX' },
            res.data,
            this.source
          );
        }
      });
    },
    handleGradeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.college) {
        this.handleCollegeChange(this.queryForm.college);
      }
    },
    // 根据年份学院查专业
    handleCollegeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.grade) {
        const params = {
          grade: this.queryForm.grade,
          college: val
        };
        this.api.getSubject(params).then(res => {
          this.source.subjectOptions = res.data;
        }).catch();
      }
    },
    // 修改
    onEdit(row) {
      this.actionType = 'EDIT';
      this.scoreDialogVisible = true;
      this.scoreSettingForm = { ...row };
      this.scoreSettingForm.excellentRatio = (row.excellentRatio || row.excellentRatio === 0) ? this.fixDecimalMul(row.excellentRatio, 100) : '';
      this.scoreSettingForm.fineRatio = (row.fineRatio || row.fineRatio === 0) ? this.fixDecimalMul(row.fineRatio, 100) : '';
      this.$nextTick(() => {
        this.$refs.scoreSettingForm.clearValidate();
      });
    },
    // 导出
    onExport() {
      const params = {
        scoreWeightVo: this.queryForm,
        scoreWeightDateVoList: this.scoreSelectedData
      };
      this.api.export(params).then(res => {
        if (res.code == 200) {
          // this.delayRequest(res.data.key);
          tools.downloadFile(res.data.key, "评分权重.xls", null, this);
        }
      });
    },
    // 查文件导出状态，等待导出
    async delayRequest(key) {
      await new Promise(resolve => setTimeout(resolve, 3000));
      this.api.getExportStatus(key).then(res => {
        if (res.code === 200 && res.data.status) {
          let path = 'api/designservice/common/export?path=' + res.data.path;
          window.open(path);
        } else {
          this.delayRequest(key);
        }
      }).catch(err => {
        this.delayRequest(key);
      });
    },
    // 批量修改
    onBatchEdit() {
      if (!this.scoreSelectedData.length) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectData'), this.$t('graduationDesign.prompt'));
        return;
      }
      this.actionType = 'BATCH_EDIT';
      this.scoreDialogVisible = true;
      this.scoreSettingForm.settingList = this.scoreSelectedData;
      this.scoreSettingForm.excellentRatio = "";
      this.scoreSettingForm.fineRatio = "";
      this.$nextTick(() => {
        this.$refs.scoreSettingForm.clearValidate();
      });
    },
    // 复制
    onCopy() {
      this.$eduConfirm(this.$t('graduationDesign.copyConfirm'), this.$t('graduationDesign.copy')).then(() => {
        const grade = this.currentGrade;
        this.api.copy(grade).then(res => {
          this.$message.success(this.$t('graduationDesign.copySuccess'));
          this.searchList();
        }).catch(() => { });
      }).catch(() => { });
    },
    closeDialog() {
      this.scoreDialogVisible = false;
    },
    settingListFormat(list) {
      let dataset = [];
      list.forEach(item => {
        item.excellentRatio = this.scoreSettingForm.excellentRatio;
        item.fineRatio = this.scoreSettingForm.fineRatio;
        dataset.push(item);
      });
      return dataset;
    },
    onSubmit() {
      this.$refs.scoreSettingForm.validate((valid) => {
        if (valid) {
          const totalRatio = Number(this.scoreSettingForm.excellentRatio) + Number(this.scoreSettingForm.fineRatio);
          if (totalRatio > 100) {
            this.$message.warning(this.$t('graduationDesign.excellentGoodRatioTips'));
            return false;
          }
          let params = [];
          this.scoreSettingForm.excellentRatio = this.scoreSettingForm.excellentRatio / 100;
          this.scoreSettingForm.fineRatio = this.scoreSettingForm.fineRatio / 100;
          if (this.actionType === 'EDIT') {
            params.push({ ...this.scoreSettingForm });
          } else if (this.actionType === 'BATCH_EDIT') {
            params = this.settingListFormat(this.scoreSettingForm.settingList);
          }
          this.api.update(params).then(res => {
            this.$message.success(this.$t('graduationDesign.modifySuccess'));
            this.searchList();
            this.scoreDialogVisible = false;
          }).catch(() => {
            this.scoreSettingForm.excellentRatio = this.scoreSettingForm.excellentRatio * 100;
            this.scoreSettingForm.fineRatio = this.scoreSettingForm.fineRatio * 100;
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.score-weight-setting {
    .selected-data {
        margin-bottom: 10px;
    }
    .search-item {
        width: 100%;
    }
    .ratio-color {
        color: red;
    }
}
</style>
